import React, { useState } from "react";
import { NavBar } from "antd-mobile";
import { useNavigate } from "react-router";
import { Button, Input, Form, Dialog } from "react-vant";
import http from "../../utils/http";
import styles from "./index.module.css";
import img from "./images/yi.jpg";
const Index: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  // 复选框状态
  const [checkState, setCheckState] = useState(false);
  let [time, setTime] = useState(60);
  // 随机字母
  const [name, setName] = useState("");
  // 封装倒计时
  const timeOut = () => {
    const timer = setInterval(() => {
      setTime(time--);
      if (time <= 0) {
        clearInterval(timer);
        setTime(60);
      }
    }, 1000);
  };
  // 复选框事件
  const hanCheck = () => {
    setCheckState(!checkState);
  };
  // 获取验证码
  const hanCode = async () => {
    // 获取用户名
    const username = form.getFieldsValue().username;
    if (username === undefined) {
      alert("手机号不能为空");
      return;
    }
    // 执行倒计时
    timeOut();
    // 请求后端
    const res = await http.post("/login", { params: { username } });
    const { code, data } = res.data;
    if (code === 20000) {
      Dialog.confirm({
        message: "验证码为：" + data,
      });
    }
  };
  // 登录
  const onFinish = async (values: any) => {
    // 验证手机号
    if (values !== "") {
      const usernameref = /^1[3-9]\d{9}$/;
      if (!usernameref.test(values.username)) {
        alert("手机号格式不正确");
        return;
      }
      // 生成图片
      const avator =
        "https://img0.baidu.com/it/u=2016099514,2502270429&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800";
      // 生成昵称
      let letters = "";
      const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      for (let i = 0; i < 10; i++) {
        const randomIndex = Math.floor(Math.random() * alphabet.length);
        letters += alphabet.charAt(randomIndex);
      }
      setName(letters);
      const userInfor = {
        username: values.username,
        password: values.password,
        nickname: letters,
        avator: avator,
      };
      // 验证复选框是否选中
      if (!checkState) {
        Dialog.confirm({
          message: "请先阅读并同意用户协议",
        });
        return;
      }
      localStorage.setItem("username", JSON.stringify(userInfor));

      // 跳转
      navigate("/");
    }
  };
  return (
    <div>
      <NavBar onBack={() => navigate("/")}></NavBar>
      {/* 图片 */}
      <img src={img} alt="" className={styles.img} />
      {/* 登录 */}
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div style={{ margin: "25px 35px" }}>
            <Button
              round
              nativeType="submit"
              block
              style={{ backgroundColor: "#ccc" }}
            >
              登录
            </Button>
            <div className={styles.checkbox}>
              <input
                type="checkbox"
                checked={checkState}
                onChange={() => hanCheck()}
              />
              已阅读并同意<span>《妙手医生服务协议》</span>和
              <span>
                《妙手医生隐私政策》、《妙手医生儿童个人信息保护规则》
              </span>
            </div>
          </div>
        }
      >
        <Form.Item
          rules={[{ required: false, message: "请填写用户名" }]}
          name="username"
          label=""
          style={{ marginTop: "10px" }}
        >
          <Input
            disabled={time !== 60}
            prefix={<span className={styles.sum}>+86</span>}
            placeholder="输入手机号"
          />
        </Form.Item>
        <Form.Item
          rules={[{ required: false, message: "请填写验证码" }]}
          name="password"
          style={{ marginLeft: "40px" }}
        >
          <Input
            suffix={
              <Button
                disabled={time !== 60}
                className={styles.code}
                onClick={() => hanCode()}
              >
                {time === 60 ? "获取验证码" : time + "s后重新获取"}
              </Button>
            }
            placeholder="请输入验证码"
          />
        </Form.Item>
      </Form>
    </div>
  );
};

export default Index;
